package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.DishDto;
import com.itheima.mapper.DishFlavorMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Override
    public void saveDishAndFlavor(DishDto dishDto) {
        //1、保存菜品 dish
        dishMapper.insert(dishDto);

        //2、保存口味 dish_flavor
        List<DishFlavor> flavors = dishDto.getFlavors();
        if(flavors!=null && flavors.size()>0){
            for (DishFlavor flavor : flavors) {
                //设置口味对应的菜品id
                Long id = dishDto.getId();
                flavor.setDishId(id);
                dishFlavorMapper.insert(flavor);
            }
        }
    }

    @Override
    public DishDto queryDishById(Long id) {
        //1、查询菜品数据
        Dish dish = dishMapper.selectById(id);

        //2、查询口味数据
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(qw);

        //3、菜品数据和口味数据 DishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    @Override
    public void updateDishAndFlavor(DishDto dishDto) {
        //1、更新菜品数据 update dish set xxx=?,... where id =?
        dishMapper.updateById(dishDto);

        //2、更新口味数据
        //2.1 先删除菜品对应的口味数据 delete from dish_flavor where dish_id = ?
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        Long dishId = dishDto.getId();
        qw.eq(DishFlavor::getDishId,dishId);
        dishFlavorMapper.delete(qw);

        //2.2 添加菜品对应的口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        if(flavors!=null && flavors.size()>0){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
                dishFlavorMapper.insert(flavor);
            }
        }
    }


}
